//
//  UniversityProfessionalTableViewController.m
//  大学专业的 省份列表页面
//
//  Created by 唐秦崴 on 15/3/14.
//  Copyright (c) 2015年 Lizzy. All rights reserved.
//

#import "UniversityProfessionalTableViewController.h"
#import "ProvinceUniversityViewController.h"
#import "SearchUniversityViewController.h"
#import "University.h"
#import <BmobSDK/Bmob.h>

@interface UniversityProfessionalTableViewController ()

@property (nonatomic,strong) NSMutableArray* universitysForSelectedProvince;


@end

@implementation UniversityProfessionalTableViewController

static const int BMOBQUERY_LIMIT = 1000;  // Bmob 单次查询数据数目的上限

// 重写getter，防止addObject的时候该属性为nil
-( NSMutableArray* ) universitysForSelectedProvince
{
    if (!_universitysForSelectedProvince) { _universitysForSelectedProvince = [[ NSMutableArray alloc ] init ]; };
    return _universitysForSelectedProvince;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 设置返回按钮的颜色
    self.navigationController.navigationBar.tintColor = [ UIColor whiteColor ];
    // 设置返回按钮文字
    // Set this in every view controller so that the back button displays back instead of the root view controller name
    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil];

    
    // 设置分割线样式
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    self.tableView.separatorColor = [UIColor colorWithRed:236/255.0 green:208/255.0 blue:191/255.0 alpha:1 ];
    
    /// 添加文字内容
    self.textLabelMArray = @[ @"浙江省",@"安徽省",@"澳门特别行政区",@"北京市",@"重庆市",@"福建省",@"甘肃省",@"广东省",
                                             @"广西壮族自治区",@"贵州省", @"海南省",@"河北省",@"河南省",@"黑龙江省",@"湖北省",@"湖南省",@"吉林省",@"江苏省",@"江西省",@"辽宁省",@"内蒙古自治区",@"宁夏回族自治区",@"青海省",@"山东省",
                                             @"山西省",@"陕西省",@"上海市",@"四川省",@"台湾省",@"天津市",@"西藏藏族自治区",@"香港特别行政区",@"新疆维吾尔自治区",@"云南省"];
    
    // 添加图片
    NSMutableArray *imagesArray     = [NSMutableArray array];
    
    // 添加图片数组内容
    for(NSInteger index = 0;index<[ self.textLabelMArray count];index++){
        UIImage *image      = [UIImage imageNamed:[ self.textLabelMArray objectAtIndex:index ] ];
        [imagesArray addObject:image];
    }
    
    // 图片数组赋值
    self.imageMArray     = [[NSArray alloc] initWithArray:imagesArray];
//    NSLog(@"多少行  :   %lu", [self.textLabelMArray count] );
    

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

//- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
//    // Return the number of sections.
//    return 1;
//}

// tableView每个分区的行数，可以为各个分区设置不同的行数，根据section的值判断即可
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [ self.textLabelMArray count ];
}

// 实现每一行Cell的内容，tableView重用机制
static const float CELL_ARROW_X       = 280;
static const float CELL_ARROW_Y       = 10;
static const float CELL_ARROW_HEIGHT  = 20;
static const float CELL_ARROW_WIDTH   = 20;
-(UITableViewCell* ) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString* cellIdentifier = @"cellIdentifier";
    
    UITableViewCell* cell = [ tableView dequeueReusableCellWithIdentifier:cellIdentifier ];
    
    if ( nil == cell ) {
        
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
    
    cell.textLabel.text  = [self.textLabelMArray objectAtIndex:indexPath.row ];
    // 设置每一行的图片
    cell.imageView.image = [self.imageMArray objectAtIndex:indexPath.row];
    
    // 设置右侧小箭头
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setBackgroundImage:[UIImage imageNamed:@"arrow_right_orange"] forState:UIControlStateNormal];
    [button setFrame:CGRectMake( CELL_ARROW_X , CELL_ARROW_Y, CELL_ARROW_WIDTH, CELL_ARROW_HEIGHT)];
    [cell.contentView addSubview:button];
    
    return cell;
}

// 设置选中某行的处理
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if( 0 == indexPath.section )
    {
        NSLog(@"you chosed row: %lu", indexPath.row ); //test
        
        // 清空 大学的数组
        [ self.universitysForSelectedProvince removeAllObjects ];
        
        // Bmob查询
        BmobQuery   *bquery = [BmobQuery queryWithClassName:@"University"];
        bquery.limit = BMOBQUERY_LIMIT;
        [bquery orderByAscending:@"order"];
        [bquery whereKey:@"province" equalTo: [ self.textLabelMArray objectAtIndex:indexPath.row ]];
        [bquery findObjectsInBackgroundWithBlock:^(NSArray *array, NSError *error) {
            
//            NSLog( @" array count ： %lu", [ array count ] );
            for (BmobObject *obj in array) {
               
//                NSLog(@"obj.playerName = %@", [obj objectForKey:@"playerName"]);
                University* university = [[ University alloc ] initWithBmobObject:obj];
                [ self.universitysForSelectedProvince addObject:university ];
                
            }
            
            [ self performSegueWithIdentifier:@"provinceUniversity" sender:self ];
        }];
        
        
    }
    else 
    {
        NSLog( @"You chosed section unknown , row： %lu", indexPath.row );
        return ;
    }
    
}

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([segue.identifier isEqualToString:@"provinceUniversity"]) {
        if ([segue.destinationViewController isKindOfClass: [ProvinceUniversityViewController class]]) {
            ProvinceUniversityViewController* puVC = (ProvinceUniversityViewController*)segue.destinationViewController;
            puVC.universitysArray = [[ NSMutableArray alloc ] initWithArray: self.universitysForSelectedProvince ];
        }
    }
    else if([segue.identifier isEqualToString:@"searchUniversity"]) {
        if ([segue.destinationViewController isKindOfClass: [ SearchUniversityViewController class]]) {
            SearchUniversityViewController* suVC = (SearchUniversityViewController*)segue.destinationViewController;
            
            // 查出所有的大学
            // 清空 大学的数组
            [ self.universitysForSelectedProvince removeAllObjects ];
            
            // Bmob查询
            BmobQuery   *bquery = [BmobQuery queryWithClassName:@"University"];
            bquery.limit = BMOBQUERY_LIMIT;
//            [bquery orderByAscending:@"order"];
            [bquery findObjectsInBackgroundWithBlock:^(NSArray *array, NSError *error) {
       
                for (BmobObject *obj in array) {
            
                    University* university = [[ University alloc ] initWithBmobObject:obj];
                    [ self.universitysForSelectedProvince addObject:university ];
                }
                
                suVC.universityArray = [[ NSMutableArray alloc ] initWithArray:self.universitysForSelectedProvince];
                
                // 所有大学的数据读取到了，就设置搜索的数组
                [suVC setUpQuickSearch ];

            }];
            
            
        }
    }
}


@end
